<template>
  <div class="login-container">
    <!-- 顶部 -->
    <div class="absolute-lt flex-x-end p-3 w-full">
      <el-switch
        v-model="isDark"
        inline-prompt
        :active-icon="Moon"
        :inactive-icon="Sunny"
        @change="toggleTheme"
      />
      <lang-select class="ml-2 cursor-pointer" />
    </div>
    <!-- 登录表单 -->
    <el-card
      v-if="chkLoginTypeObj.active"
      class="login-input-container !border-none !bg-transparent !rounded-[4%] w-100 <sm:w-85"
    >
      <div class="text-center relative">
        <h2>
          {{ settingsStore.getSystemName }}-{{
            chkLoginTypeObj.list.find((item) => item.identity === chkLoginTypeObj.active)
              .name
          }}
        </h2>
        <!-- <el-tag class="ml-2 absolute-rt">{{ defaultSettings.version }}</el-tag> -->
      </div>

      <el-form
        ref="loginFormRef"
        :model="loginData"
        :rules="loginRules"
        class="login-form"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="user" class="mx-2" />
            <el-input
              ref="username"
              v-model="loginData.username"
              :placeholder="$t('login.username')"
              name="username"
              size="large"
              class="h-[48px]"
            />
          </div>
        </el-form-item>

        <!-- 密码 -->
        <el-tooltip
          :visible="isCapslock"
          :content="$t('login.capsLock')"
          placement="right"
        >
          <el-form-item prop="password">
            <div class="flex-y-center w-full">
              <svg-icon icon-class="lock" class="mx-2" />
              <el-input
                v-model="loginData.password"
                :placeholder="$t('login.password')"
                type="password"
                name="password"
                @keyup="checkCapslock"
                @keyup.enter="handleLogin"
                size="large"
                class="h-[48px] pr-2"
                show-password
              />
            </div>
          </el-form-item>
        </el-tooltip>

        <!-- 验证码 -->
        <el-form-item prop="captchaKey">
          <div class="flex-y-center w-full">
            <svg-icon icon-class="captcha" class="mx-2" />
            <el-input
              v-model="loginData.captchaKey"
              auto-complete="off"
              size="large"
              class="flex-1"
              placeholder="请输入验证码"
              @keyup.enter="handleLogin"
            />

            <div
              @click="getCaptcha"
              v-html="captchaBase64"
              class="rounded-tr-md rounded-br-md cursor-pointer h-[48px]"
            ></div>
            <!-- <img @click="getCaptcha" :src="captchaBase64"
              class="rounded-tr-md rounded-br-md cursor-pointer h-[48px]" /> -->
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-button
          :loading="loading"
          type="primary"
          size="large"
          class="w-full"
          @click.prevent="handleLogin"
          >{{ $t("login.login") }}
        </el-button>

        <!-- 账号密码提示 -->
        <!-- <div class="mt-10 text-sm">
          <span>{{ $t("login.username") }}: admin</span>
          <span class="ml-4"> {{ $t("login.password") }}: 123123</span>
        </div> -->
      </el-form>
    </el-card>
    <el-card
      v-show="!chkLoginTypeObj.active"
      class="!border-none !bg-transparent !rounded-[4%] w-100 <sm:w-85 -mt-[60px]"
    >
      <div class="text-center relative">
        <h2>请选择登录类型</h2>
        <!-- <el-tag class="ml-2 absolute-rt">{{ defaultSettings.version }}</el-tag> -->
      </div>
      <div flex justify-center flex-items-center h-100px>
        <el-space>
          <el-radio-group
            v-model="chkLoginTypeObj.active"
            size="large"
            @change="handleChangLoginType"
          >
            <el-radio-button
              v-for="(item, index) in chkLoginTypeObj.list"
              :key="index"
              :label="item.name"
              :value="item.identity"
            />
          </el-radio-group>
        </el-space>
      </div>
    </el-card>

    <!-- ICP备案 -->
    <div class="absolute bottom-1 text-[10px] text-center" v-show="icpVisible">
      <p>Copyright © 2024 xuedai.tech All Rights Reserved. 希任戋技术 版权所有</p>
      <p>湘ICP备00000000号-0</p>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
      @closed="closedDialog"
    >
      <Google v-model:secret="googleCodeObj.secret" v-model:input="googleCodeObj.code" />
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="dialog.leftBtnText" type="primary" @click="handleLeftClick">{{
            dialog.leftBtnText
          }}</el-button>
          <el-button v-if="dialog.rightBtnText" @click="handleRightClick">{{
            dialog.rightBtnText
          }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useSettingsStore, useUserStore } from "@/store";
import { getCaptchaApi } from "@/api/auth";
import { LoginData } from "@/api/auth/types";
import { Sunny, Moon } from "@element-plus/icons-vue";
import { LocationQuery, LocationQueryValue, useRoute } from "vue-router";
import router from "@/router";
import defaultSettings from "@/settings";
import { ThemeEnum } from "@/enums/ThemeEnum";
import { cloneDeep } from "lodash";

// import { supportedChains, getAllCoins } from "@/api/test";

// supportedChains().then(res => {
//   console.log(res);
// }).catch(error => {
//   // 处理错误
//   console.error('Error fetching supported chains:', error);
// });


import {
  getGoogleCode as getCodeByOther,
  getBind as getBindByOther,
} from "@/api/other/user";
import {
  getCode as getCodeByPayee,
  getBind as getBindByPayee,
} from "@/api/payee/account";
import { getCode as getCodeByPayer, getBind as getBindByPayer } from "@/api/payer/order";
// import { getSystemName } from "@/composition/system-name.vue";

const loginTypeArr = ["web"];

// Stores
const userStore = useUserStore();
const settingsStore = useSettingsStore();

// Internationalization
const { t } = useI18n();

const route = useRoute();

const googleCodeObj = ref({
  secret: "",
  code: "",
});

// Reactive states
const isDark = ref(settingsStore.theme === ThemeEnum.DARK);
const icpVisible = ref(true);
const loading = ref(false); // 按钮loading
const isCapslock = ref(false); // 是否大写锁定
const captchaBase64 = ref(); // 验证码图片Base64字符串
const loginFormRef = ref(ElForm); // 登录表单ref
const { height } = useWindowSize();

const loginType = ref("");

const loginData = ref<LoginData>({
  // username: "admin",
  // password: "123123",
  username: "",
  password: "",
  // google_code: "",
  captchaKey: "",
});

function getLoginData() {
  let result: any = loginData.value;

  const tempLoginType = chkLoginTypeObj.value.active;

  if (tempLoginType === "payer") {
    result = {
      ...loginData.value,
      mer_name: loginData.value.username,
    };
  } else if (tempLoginType === "payee") {
    result = {
      ...loginData.value,
      ms_name: loginData.value.username,
    };
  }

  return result;
}

const loginRules = computed(() => {
  return {
    // username: [
    //   {
    //     required: true,
    //     trigger: "blur",
    //     message: t("login.message.username.required"),
    //   },
    // ],
    // password: [
    //   {
    //     required: true,
    //     trigger: "blur",
    //     message: t("login.message.password.required"),
    //   },
    //   {
    //     min: 6,
    //     message: t("login.message.password.min"),
    //     trigger: "blur",
    //   },
    // ],
    // google_code: [
    //   {
    //     required: true,
    //     trigger: "blur",
    //     message: t("login.message.google_code.required"),
    //   },
    // ],
  };
});

/**
 * 获取验证码
 */
function getCaptcha() {
  getCaptchaApi().then((res) => {
    // loginData.value.captchaKey = res.captchaKey;
    captchaBase64.value = res;
  });
}

function successPageSkip() {
  const redirect = "/" + chkLoginTypeObj.value.active;

  router.push({ path: redirect });
}

/**
 * 登录
 */
function handleLogin() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;

      const params = getLoginData();

      userStore
        .login(params)
        .then((res) => {
          // if (params.google_code) {
          //   // const query: LocationQuery = route.query;
          //   // const redirect = (query.redirect as LocationQueryValue) ?? "/";
          //   const redirect = "/" + chkLoginTypeObj.value.active;
          //   // const otherQueryParams = Object.keys(query).reduce((acc: any, cur: string) => {
          //   //   if (cur !== "redirect") {
          //   //     acc[cur] = query[cur];
          //   //   }
          //   //   return acc;
          //   // }, {});

          //   // router.push({ path: redirect, query: otherQueryParams });

          //   router.push({ path: redirect });
          // } else {
          //   dialog.visible = true;
          //   // 谷歌验证
          //   dialog.width = 600;
          //   dialog.title = "绑定Google";
          //   dialog.leftBtnText = "确 定";
          //   dialog.rightBtnText = "取 消";
          // }

          successPageSkip();
        })
        .catch(() => {
          getCaptcha();
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/**
 * 主题切换
 */

const toggleTheme = () => {
  const newTheme =
    settingsStore.theme === ThemeEnum.DARK ? ThemeEnum.LIGHT : ThemeEnum.DARK;
  settingsStore.changeTheme(newTheme);
};
/**
 * 根据屏幕宽度切换设备模式
 */

watchEffect(() => {
  if (height.value < 600) {
    icpVisible.value = false;
  } else {
    icpVisible.value = true;
  }
});

/**
 * 检查输入大小写
 */
function checkCapslock(event: KeyboardEvent) {
  // 防止浏览器密码自动填充时报错
  if (event instanceof KeyboardEvent) {
    isCapslock.value = event.getModifierState("CapsLock");
  }
}

/**
 * 登录类型判断
 */
// 定义一个用于保存登录类型信息的 ref 变量 chkLoginTypeObj
const chkLoginTypeObj = ref({
  // 当前激活的登录类型
  active: "",
  // 登录类型列表
  list: [
    {
      // 标识：other，用于用户登录类型，默认为三方
      identity: "web",
      // 名称：三方，用于用户登录类型
      name: "总后台",
    },
    // {
    //   // 标识：payer，用于用户登录类型，默认为商户平台
    //   identity: "payer",
    //   // 名称：商户平台，用于用户登录类型
    //   name: "商户后台",
    // },
    // {
    //   // 标识：payee，用于用户登录类型，默认为码商管理后台
    //   identity: "payee",
    //   // 名称：码商管理后台，用于用户登录类型
    //   name: "码商后台",
    // },
  ],
});

// 处理修改登录类型的事件
function handleChangLoginType(val) {
  // 获取当前激活的登录类型
  const tempLoginType = val;

  // 如果存在激活的登录类型，则跳转到对应的登录页面
  if (tempLoginType) {
    loginData.value.loginType = tempLoginType;
    // localStorage.setItem("loginType", loginType);
    console.log(tempLoginType);
    loginType.value = tempLoginType;
    userStore.SET_LOGIN_TYPE(tempLoginType);
    // handleLogin();
    // router.push({ path: "/" + loginType });
  }
}

const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 400,
  title: "",
  leftBtnText: "确 定",
  rightBtnText: "",
});
const dialogBak = cloneDeep(dialog);

function handleLeftClick() {
  // 谷歌验证
  let params = { ...googleCodeObj.value };

  // params.pass_show = params.pass_show ? 1 : 2;
  // params.order_float_amount = params.order_float_amount ? 1 : 2;
  // params.pay_page_sub_name = params.pay_page_sub_name ? 1 : 2;
  // params.int_skm_amount = params.int_skm_amount ? 1 : 2;
  // params.skm_amount_range = params.skm_amount_range ? 1 : 2;
  // params.handle_order_status = params.handle_order_status ? 1 : 2;
  // params.status = params.status ? 1 : 2;

  const loginType = userStore.getLoginType();

  const getBind =
    loginType == "other"
      ? getBindByOther
      : loginType == "payee"
      ? getBindByPayee
      : getBindByPayer;

  getBind(params).then((res) => {
    ElMessage.success("绑定google验证成功，请再次登录");
    closeDialog();
  });
}
function handleRightClick() {
  // formDialogId.
  closeDialog();
}
function closeDialog() {
  dialog.visible = false;
}
function closedDialog() {
  // formDialogId.value?.resetFields();
  // formDialogId.value?.clearValidate();
  formDialogId.value = {};
  formDialogModel.value = {};
  initDialogForm.value.initKeys.splice(0);
  Object.keys(dialogBak).map((key) => {
    dialog[key] = dialogBak[key];
  });

  initDialogForm.value = cloneDeep(initDialogFormBak);
}

let formDialogModel = ref({});

// 修改 chkLoginTypeObj 的值，使其与路由参数保持一致
chkLoginTypeObj.value.active = 'web';
// chkLoginTypeObj.value.active = (route.params?.identity || "web") + "";
if (
  !!loginType.value &&
  loginType.value !== chkLoginTypeObj.value.active &&
  !loginTypeArr.includes(chkLoginTypeObj.value.active)
) {
  localStorage.clear();
  router.push({ path: "/login", replace: true });
}
// console.log(chkLoginTypeObj.value.active);
// localStorage.setItem("loginType", chkLoginTypeObj.value.active);
// sessionStorage.setItem("loginType", chkLoginTypeObj.value.active);
userStore.SET_LOGIN_TYPE(chkLoginTypeObj.value.active);
loginType.value = chkLoginTypeObj.value.active;

const accessToken = localStorage.getItem(loginType.value + "accessToken");

if (accessToken) {
  // 获取用户信息
  successPageSkip();
}
/**
 * **********************完**********************
 */

onMounted(() => {
  getCaptcha();

  if (chkLoginTypeObj.value.active) {
    // handleLogin();
  }
});

watch(
  () => route.path,
  (newVal: string) => {
    if (newVal.startsWith("/login/")) {
      if (chkLoginTypeObj.value.active) {
        // handleLogin();
      }
    }
  }
);
</script>

<style lang="scss" scoped>
html.dark .login-container {
  background: url("@/assets/images/login-bg-dark.jpg") no-repeat center right;
}

.login-container {
  overflow-y: auto;
  background: url("@/assets/images/login-bg.jpg") no-repeat center right;

  @apply wh-full flex-center;

  .login-form {
    padding: 30px 10px;
  }
}

.el-form-item {
  background: var(--el-input-bg-color);
  border: 1px solid var(--el-border-color);
  border-radius: 5px;
}

.login-input-container {
  :deep(.el-input) {
    .el-input__wrapper {
      padding: 0;
      background-color: transparent;
      box-shadow: none;

      &.is-focus,
      &:hover {
        box-shadow: none !important;
      }

      input:-webkit-autofill {
        /* 通过延时渲染背景色变相去除背景颜色 */
        transition: background-color 1000s ease-in-out 0s;
      }
    }
  }
}
</style>
